#include "bin_gradient.h"

BinarizationGradient::BinarizationGradient(PNM* img) :
    Transformation(img)
{
}

BinarizationGradient::BinarizationGradient(PNM* img, ImageViewer* iv) :
    Transformation(img, iv)
{
}

PNM* BinarizationGradient::transform()
{
    int width = image->width();
    int height = image->height();

    PNM* newImage = new PNM(width, height, QImage::Format_Mono);

	if (image->format() == QImage::Format_Indexed8)
	{
		int l = 0;
		int m = 0;
		int T;

		for (int i = 1; i < width-1; i++)
		{
			for (int j = 1; j < height - 1; j++)
			{
				QRgb pixel = image->pixel(i,j);

				QRgb pixelX1 = image->pixel(i-1,j);
				QRgb pixelX2 = image->pixel(i+1,j);
				QRgb pixelY1 = image->pixel(i,j-1);
				QRgb pixelY2 = image->pixel(i,j+1);

				auto val = qGray(pixel);
				auto gradX = qGray(pixelX2) - qGray(pixelX1);
				auto gradY = qGray(pixelY2) - qGray(pixelY1);

				auto G = std::max(gradX, gradY);
				
				l += G * val;
				m += G;
			}
		}

		T = l / m;

		for (int i = 0; i < width; i++)
		{
			for (int j = 0; j < height; j++)
			{
				QRgb pixel = image->pixel(i,j);
				if(qGray(pixel) <= T) newImage->setPixel(i, j, 0);
				else newImage->setPixel(i, j, 1);
			}
		}

	}
	else {
		qDebug() << Q_FUNC_INFO << "Image should be gray scaled";
	}

    return newImage;
}


